/*
 * fs.c
 *
 *  Created on: 13/11/2011
 *      Author: MadeyMaga
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "nipc.h"
#include "config.h"
#include "pedidos.h"
#include "Planificador.h"
#include "fs.h"

//extern t_log 	*s_log;
extern int 		maxfs;


void atenderFs(int fdCon)
{
	unsigned int 	sector;
	char 			*bufSector;
	nipcMessage 	msg;

	nipc_recv(&msg, fdCon);

	sector = atoi(strtok(msg.payload, ";"));

	switch(msg.type)
	{
	case LEER_C: /* LECTURA ("NumeroSector;") */
		bufSector = "";
		agregarPedido(sector, READ, P_FS, bufSector, fdCon);
//		log_info(s_log, "thread-fs", "Message info: %s %d", "se realizo un pedido de lectura del sector", sector);
		break;
	case ESCRIBIR_C:/* ESCRITURA ("NumeroSector;Buffer") */
		bufSector = strtok(NULL, "\0");
		agregarPedido(sector, WRITE, P_FS, bufSector, fdCon);
//		log_info(s_log, "Thread-FileSystem", "Message info: %s %d", "se realizo un pedido de escritura del sector", sector);
		break;
	}
}

int crearSockFsListener()
{
	int 	fsport, fdSocket;
	char 	localip[16];

	getConfig("fsport", &fsport);
	getConfig("localip", &localip);

	fdSocket = sockets_open_server(localip, fsport, maxfs);

	if(-1 == fdSocket)
	{
		perror("bind socket listener");
		exit(SOCKET_ERROR);
	}

	printf("Esperando conexiones con el file system...\n");

	return fdSocket;
}

void atenderFsListener(int fdPoll, int fdSocket)
{
	int 				retval, fdCon;
	unsigned int 		size;
	struct sockaddr_in 	dir;
	nipcMessage 		msg;

	fdCon = accept(fdSocket, (struct sockaddr*)&dir, &size);

	pollIn(fdCon);

	agregarFdEnTablaSock(fdCon, P_FS);

	retval = nipc_recv(&msg, fdCon);

	if((retval == NIPC_ERROR) || (msg.payloadLength != 0))
	{
		/* handshake erroneo */
		sprintf(msg.payload, "%d", HANDSHAKE_FAIL);
		nipc_send(&msg, fdCon);
		close(fdCon);
	}
	else
	{
		/* el handshake esta bien */
		msg.payload = (char *) malloc(sizeof(HANDSHAKE_OK));

		memset(msg.payloadID, 0, 6);
		sprintf(msg.payloadID, "%d", fdCon);
		msg.type = '0';
		msg.payloadLength = strlen(msg.payload) + 1;
		sprintf(msg.payload, "%d", HANDSHAKE_OK);

		/* mandamos la respuesta al handshake */
		nipc_send(&msg, fdCon);

		free(msg.payload);
	}
}

